import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import router from "@/routers";
import { LOGIN_URL } from "@/config";
import { refreshTokenApi } from "@/api/modules/login";
import RequestHttp from "@/api/index";
import type { AxiosError } from "axios";

let refreshTokenPromise: Promise<any> | null = null;

export const checkStatus = async (status: number, error: AxiosError) => {
  const userStore = useUserStore();

  // 优先处理401状态码（token相关错误）
  if (status === 401) {
    try {
      const errorData = (error.response?.data || {}) as {
        msg?: string;
        data?: string;
        code?: number;
      };

      // 明确被挤下线（来自后端 verifyToken 的 "TOKEN_REVOKED"）
      if (errorData.data === "TOKEN_REVOKED") {
        ElMessage.error("账号在其他设备登录，已被强制下线");
        userStore.setToken("");
        router.replace(LOGIN_URL);
        return;
      }

      // 明确 token 过期
      if (errorData.data === "TOKEN_EXPIRED") {
        ElMessage.error("登录已过期，请重新登录");
        userStore.setToken("");
        router.replace(LOGIN_URL);
        return;
      }

      // 如果是 access_token 失效，尝试用 refresh_token 刷新
      if (!refreshTokenPromise) {
        refreshTokenPromise = refreshTokenApi({
          refresh_token: userStore.userInfo.refresh_token
        });
      }

      const { data } = await refreshTokenPromise;
      refreshTokenPromise = null;

      // 更新 store 中的 token
      userStore.setToken(data.access_token);
      userStore.setUserInfo({
        ...userStore.userInfo,
        access_token: data.access_token,
        refresh_token: data.refresh_token,
        tokenId: data.tokenId
      });

      // 重新发起原请求
      if (error.config) {
        if (error.config.headers && typeof error.config.headers.set === "function") {
          error.config.headers.set("authorization", data.access_token);
        } else if (error.config.headers) {
          error.config.headers["authorization"] = data.access_token;
        }

        (error.config as any)._retry = true;

        return RequestHttp.service.request(error.config);
      }
    } catch (err) {
      refreshTokenPromise = null;
      userStore.setToken("");
      router.replace(LOGIN_URL);
      ElMessage.error("登录已过期，请重新登录");
    }
    return;
  }

  // 其他状态码处理
  switch (status) {
    case 403:
      ElMessage.error("无权限");
      break;

    case 404:
      ElMessage.error("你所访问的资源不存在！");
      break;

    case 405:
      ElMessage.error("请求方式错误！请您稍后重试");
      break;

    case 408:
      ElMessage.error("请求超时！请您稍后重试");
      break;

    case 500:
      ElMessage.error("服务异常！");
      break;

    case 502:
      ElMessage.error("网关错误！");
      break;

    case 503:
      ElMessage.error("服务不可用！");
      break;

    case 504:
      ElMessage.error("网关超时！");
      break;

    default:
      // 这里处理后端自定义错误信息
      if (error.response?.data) {
        const backendData = error.response.data as any;
        if (backendData.msg) {
          ElMessage.error(backendData.msg);
          return Promise.reject(backendData);
        }
      }
      ElMessage.error("请求失败！");
  }
};
